package geektime.spring.springbucks.client;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

@SpringBootApplication
@Slf4j
public class HttpUrlRestfulDemoApplication implements ApplicationRunner {

    public static void main(String[] args) {
        new SpringApplicationBuilder(HttpUrlRestfulDemoApplication.class)
                .web(WebApplicationType.NONE)
                .bannerMode(Banner.Mode.OFF)
                .run(args);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //调用produces为json的restful查询接口
        callRestfulBycontentType("http://localhost:8080/coffee/1", "application/json");
        //调用produces为xml的restful查询接口
        callRestfulBycontentType("http://localhost:8080/coffee/", "application/xml");

    }

    public void callRestfulBycontentType(String url, String contentType) throws Exception {
        URL urlUtil = new URL(url);
        HttpURLConnection urlConnnection = (HttpURLConnection) urlUtil.openConnection();
        //设定请求的方法为"POST"，默认是GET,GET方法不需要getOutputStream，故不需要getOutputStream会隐含的进行connect()，不然都会将GET请求
        //转换为POST请求，导致报错
        urlConnnection.setRequestMethod("GET");
        //设定传送的内容类型是可序列化的java对象(如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
        urlConnnection.setRequestProperty("Content-Type", contentType);
        //设置连接超时
        urlConnnection.setConnectTimeout(10000);
        //设置读取超时（从输入流读取时的超时）
        urlConnnection.setReadTimeout(20000);
        /**
         * 实际发送请求的代码段在下面
         */
        // 调用HttpURLConnection连接对象的getInputStream()函数,将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
        InputStream inputStream = urlConnnection.getInputStream(); // <===注意，实际发送请求的代码段就在这里
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
        String line = "";
        String result = "";
        for (; (line = br.readLine()) != null; result += line) {
            ;
        }
        log.info(contentType + "方式返回结果:{}", result);
        br.close();
    }


}
